package uy.com.tsi2G7.superbet.user.dao;

import java.rmi.RemoteException;
import java.util.HashSet;
import java.util.List;

import org.springframework.orm.hibernate3.HibernateTemplate;

import uy.com.tsi2G7.superbet.user.City;
import uy.com.tsi2G7.superbet.user.Country;
import uy.com.tsi2G7.superbet.user.File;
import uy.com.tsi2G7.superbet.user.Role;
import uy.com.tsi2G7.superbet.user.User;

public class UserStoreEJB implements UserStore {
	private HibernateTemplate hibernateTemplate;
	private static long userRoleId=1L;
	
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	@Override
	public void storeUser(User user) throws RemoteException, UserStoreException {
		try{
			user.setRoles(new HashSet<Role>());
			user.getRoles().add((Role) hibernateTemplate.get(Role.class, Long.valueOf(userRoleId)));
			hibernateTemplate.merge(user);
		}catch (Throwable ex){
			throw new UserStoreException(ex);
		}
	}

	@Override
	public void updateUser(User user) throws RemoteException, UserStoreException {
		try{
			hibernateTemplate.merge(user);
		}catch (Throwable ex){
			throw new UserStoreException();
		}
	}
	
	@Override
	public User getUser(String userId)throws RemoteException, UserNotFoundException{		
		try{
			return (User)hibernateTemplate.get(User.class,userId);		
		}catch(Exception e){
			throw new UserNotFoundException();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Country> getCountries() throws RemoteException, UserStoreException {
		try{
			return hibernateTemplate.loadAll(Country.class);
		}catch(Exception e){
			throw new UserStoreException(e.getMessage());
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<City> getCities(String country) throws RemoteException, UserStoreException {
		try{
			String query = "from c in class uy.com.tsi2G7.superbet.user.City where c.countryCode = '" + country + "'";
			return hibernateTemplate.find(query);
		}catch(Exception e){
			throw new UserStoreException(e.getMessage());
		}
	}


	@Override
	public void storeImage(String userId, File image) throws RemoteException,ImageStoreException {
		try{	
			image.setUser(userId);
			hibernateTemplate.merge(image);
		}catch (Throwable ex){
			throw new ImageStoreException();
		}
		
	}

	@Override
	public File getImage(String userId) throws RemoteException, ImageStoreException {
		try{
			return (File)hibernateTemplate.get(File.class,userId);		
		}catch(Exception e){
			throw new ImageStoreException();
		}
	}

	
}
